//
//  LsLocation.m
//  MIC_MoveModelExample
//
//  Created by 李爽 on 15/11/17.
//  Copyright (c) 2015年 Shawn Li. All rights reserved.
//

#import "LsLocation.h"

@interface LsLocation ()
{
    CLLocationManager *_manager;
}
@end

@implementation LsLocation
- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)startLocation {
    if ([CLLocationManager locationServicesEnabled]) {
        _manager = [[CLLocationManager alloc] init];
        
        _manager.delegate = self;
        //控制定位精度，越高耗电量越大
        _manager.desiredAccuracy = kCLLocationAccuracyBest;
        //控制定位服务更新频率。单位米
        _manager.distanceFilter = LocationDistance;
        
        [_manager startUpdatingLocation];
        
        if (![LsGlobal isSystemLowIOS8]) {
            [_manager requestAlwaysAuthorization];
        }
    }
}

- (void)searchCityName:(CLLocation *)location {
    CLGeocoder *coder = [[CLGeocoder alloc] init];
    
    //反编码地理位置
    [coder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark *mark in placemarks) {
            BASE_INFO_FUN(mark.name);
            BASE_INFO_FUN(mark.locality);
            NSString *cityName = [mark.locality stringByReplacingOccurrencesOfString:CitySuffix withString:@""];
            
            [self.delegate didLocationAddress:mark.name];
            [self.delegate didLocationCity:cityName];
        }
    }];
}

//改变授权
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    BASE_ERROR_FUN(([NSString stringWithFormat:@"status:%@",@(status)]));
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    LSLog(@"newlocation -- %@",newLocation);
    [self searchCityName:newLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *newLocation = [locations firstObject];
    [self searchCityName:newLocation];
    LSLog(@"last location -- %@",[locations lastObject]);
    //停止更新位置（如果定位服务不需要实时更新的话，那么应该停止位置的更新）
    [_manager stopUpdatingLocation];
}
@end
